/* eslint-disable no-param-reassign */
/**
 *
 * @param hex hex颜色字符
 * @param lum 整数0-1，正数表示颜色变浅多少，否则反之
 * @returns hex
 */
export function colorLuminance(hex: string, lum: number) {
  // validate hex string
  // eslint-disable-next-line no-param-reassign
  hex = String(hex).replace(/[^0-9a-f]/gi, '')
  if (hex.length < 6) {
    hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]
  }

  lum = lum || 0

  // convert to decimal and change luminosity
  let rgb = '#',
    c,
    i

  for (i = 0; i < 3; i++) {
    c = parseInt(hex.substring(i * 2, i * 2 + 2), 16)
    c = Math.round(Math.min(Math.max(0, c + c * lum), 255)).toString(16)
    rgb += ('00' + c).substring(c.length)
  }
  return rgb
}

/**
 *
 * @param hex hex颜色字符
 * @desc 根据传入的颜色来判断返回深色还是白色
 * @returns hex
 */
export function getContrast(hex: string) {
  const r = parseInt(hex.substring(1, 2), 16),
    g = parseInt(hex.substring(3, 2), 16),
    b = parseInt(hex.substring(5, 2), 16),
    yiq = (r * 299 + g * 587 + b * 114) / 1000
  return yiq >= 128 ? '#001f3f' : '#F6F5F7'
}
